# Kestrel: An XMPP-based Many-Task Computing Scheduler
# Author: Lance Stout <lancestout@gmail.com>
#
# Copyright 2009-2010 Clemson University
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""
Roles are groups of modules that can be treated as a single
unit that provides some integrated functionality.
"""

from module import Module


class Role(Module):
    """
    A role is a collection of modules that can be started and
    stopped as a group.
    """

    def __init__(self, name):
        super(Role, self).__init__(name)
        self.modules = []

    def add_module(self, module):
        """
        Include a module in this role. When the role is started
        or stopped, the module will also be started or stopped.
        """
        self.modules.append(module)
        module.events['%s/start' % self.name] = module.start
        module.events['%s/stop' % self.name] = module.stop

    def register(self, kernel):
        """
        Register the event handlers of the role's modules with
        the application kernel.
        """
        self.kernel = kernel
        for module in self.modules:
            module.register(kernel)
        super(Role, self).register(kernel)

    def unregister(self):
        """
        Unregister the event handlers of the role's modules with
        the application kernel.
        """
        super(Role, self).unregister()
        for module in self.modules:
            module.unregister()
